import Vue from 'vue'
import VueRouter from 'vue-router'

// 引入store
import store from '@/store'

import Course from '@/views/course'
Vue.use(VueRouter)

const routes = [
  // 登录页
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: 'login' */'@/views/login/index')
  },
  // 首页（选课页）
  {
    path: '/',
    name: 'course',
    // component: () => import(/* webpackChunkName: 'course' */'@/views/course/index')
    component: Course
  },
  // 学习
  {
    path: '/learn',
    name: 'learn',
    component: () => import(/* webpackChunkName: 'learn' */'@/views/learn/index'),
    meta: { requiresAuth: true }
  },
  // 用户
  {
    path: '/user',
    name: 'user',
    component: () => import(/* webpackChunkName: 'user' */'@/views/user/index'),
    meta: { requiresAuth: true }
  },
  // 课程信息
  {
    path: '/course-info/:courseId',
    name: 'course-info',
    component: () => import(/* webpackChunkName: 'course-info' */'@/views/course-info/index'),
    props: true
  },
  // 课时视频
  {
    path: '/course-info/:lessonId/video',
    name: 'course-video',
    component: () => import(/* webpackChunkName: 'course-video' */'@/views/course-info/video'),
    props: true
  },
  // 支付课程
  {
    path: '/pay/:courseId',
    name: 'pay',
    component: () => import(/* webpackChunkName: 'pay' */'@/views/pay/index'),
    props: true
  },
  // 错误页
  {
    path: '*',
    name: 'error-page',
    component: () => import(/* webpackChunkName: 'error-page' */'@/views/error-page')
  }
]

const router = new VueRouter({
  routes
})
// 设置导航守卫进行登录检测及跳转
router.beforeEach((to, from, next) => {
  // 检测to的路由是否需要身份认证
  // 一个路由匹配到的所有路由记录都会暴露为$toute对象的$toute.matched数组,遍历数组看是否有meta信息
  if (to.matched.some(records => records.meta.requiresAuth)) {
    // 验证vuex的store 中的登录用户信息是否存储
    if (!store.state.user) {
      // 未登录 跳转到登录页并且存储当前的fullPath
      return next({
        name: 'login',
        // 存储当前的路径
        query: {
          redirect: to.fullPath
        }
      })
    }
    // 已经登录允许通过
    next()
  } else {
    next()
  }
})
export default router
